package com.example.rocketmqdemo.transaction.app;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.dto.Response;
import com.example.rocketmqdemo.transaction.client.AccountAppService;
import com.example.rocketmqdemo.transaction.domain.gateway.TransactionMessageGateway;
import com.example.rocketmqdemo.transaction.domain.transactionexecutor.LocalTransactionExecutor;
import com.example.rocketmqdemo.transaction.domain.transactionexecutor.LocalTransactionExecutorFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@CatchAndLog
@Slf4j
@Service
public class AccountAppServiceImpl implements AccountAppService {

    @Autowired
    private TransferCmdExecutor transferCmdExecutor;
    @Autowired
    private TransactionMessageGateway transactionMessageGateway;

    @Override
    public Response transfer(BigDecimal amount) {

        LocalTransactionExecutor<?> localTransactionExecutor = LocalTransactionExecutorFactory.get(
                () -> transferCmdExecutor.execute("A", "B", amount));
        String body = "A -> B " + amount;
        sendMessage(body, localTransactionExecutor);

        Object result = localTransactionExecutor.getResult();
        log.info("本地事务执行结果: {}", result);

        return Response.buildSuccess();
    }

    private void sendMessage(String body, LocalTransactionExecutor<?> localTransactionExecutor) {
        transactionMessageGateway.send(TOPIC_ACCOUNT_TRANSFER, body, localTransactionExecutor);
    }
}
